package com.dianrui.agent.activity;

import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.dianrui.agent.Constant;
import com.dianrui.agent.R;
import com.dianrui.agent.adapter.StatementAdapter;
import com.dianrui.agent.bean.FinanceList;
import com.dianrui.agent.util.DateUtil;
import com.dianrui.agent.okhttp.OkHttpRequest;
import com.dianrui.agent.util.SharedUtil;
import com.dianrui.agent.util.StringUtils;
import com.dianrui.agent.util.ToastUtil;
import com.dianrui.agent.util.Url;
import com.dianrui.agent.view.calendar.CalendarView;
import com.google.gson.JsonObject;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class StatementAccountsActivity extends BaseActivity {
    private List<FinanceList> finaceListAll = new ArrayList<>();
    private StatementAdapter statementAdapter;
    private String mstartTime;
    private String mendTime;

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.statement_list)
     ListView statementList;
    @BindView(R.id.emptyView)
    LinearLayout emptyView;
    @BindView(R.id.top_right_img)
    ImageView topRightImg;
    @BindView(R.id.current_date)
    TextView currentDate;


    @Override
    public int getContentViewId() {
        return R.layout.statement_list;
    }

    @Override
    public void initView() {
        loadDate();
        title.setText("财务记录");
        statementAdapter = new StatementAdapter(StatementAccountsActivity.this, finaceListAll);
        statementList.setAdapter(statementAdapter);
        statementAdapter.setOnStatementClickListener(new StatementAdapter.StatementClickListener() {
            @Override
            public void onOnclick(String orderCount, String createTime,String areaoutside, String networkside, String money, String discount, String wxfee, String alifee, String total,String noPay, String overtimePayment) {
                Intent intent=new Intent(StatementAccountsActivity.this,FinaceDetailActivity.class);
                intent.putExtra("start_time",createTime);
                intent.putExtra("end_time",createTime);
                startActivity(intent);
            }

            @Override
            public void onOnLastclick(String refundCard,String buyCard,String violationPrice,String orderCount,int position, List<FinanceList> financeList, String time, String curretDate,String total, String money, String discount, String noPay, String overtimePayment, String payFee) {
                Intent intent=new Intent(StatementAccountsActivity.this,FinaceDetailActivity.class);
                //FinaceInfosActivity

                intent.putExtra("start_time",mstartTime);
                intent.putExtra("end_time",mendTime);
                startActivity(intent);
            }
        });

    }

    private void loadDate() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, 0);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        String firstDay = format.format(cal.getTime());//获取本月的第一天

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());
        String today = simpleDateFormat.format(date);//获取今天


        currentDate.setText(firstDay+"至"+today);

        mstartTime=firstDay;

        mendTime=today;

        requestFinance(mstartTime,mendTime);
    }

    private void requestFinance(String firstDay,String today) {
        JsonObject finaceListJson = new JsonObject();
        if (!StringUtils.isEmpty(mstartTime)) {
            finaceListJson.addProperty("start_time", mstartTime);
        }
        if (!StringUtils.isEmpty(mendTime)) {
            finaceListJson.addProperty("end_time", mendTime);
        }
        OkHttpRequest.getInstance().postTokenRequests(SharedUtil.getUrl() + Url.FINANICE_LIST,
                finaceListJson.toString(), new OkHttpRequest.XCallBack() {

            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result) && !isFinishing()) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if ("1000".equals(jsonObject.optString("status"))) {
                            if (finaceListAll != null) {
                                finaceListAll.clear();
                            }
                            JSONArray jsonArray = jsonObject.optJSONArray("data");
                            if (jsonArray.length() > 0) {
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    FinanceList financeList = new FinanceList();
                                    financeList.create_time = jsonArray.optJSONObject(i).optString("create_time");
                                    financeList.money = jsonArray.optJSONObject(i).optString("money");
                                    financeList.discount = jsonArray.optJSONObject(i).optString("discount");
                                    financeList.total = jsonArray.optJSONObject(i).optString("total");
                                    financeList.network_outside = jsonArray.optJSONObject(i).optString("network_outside");
                                    financeList.pay_fee = jsonArray.optJSONObject(i).optString("pay_fee");
                                    financeList.no_pay = jsonArray.optJSONObject(i).optString("no_pay");
                                    financeList.overtime_payment = jsonArray.optJSONObject(i).optString("overtime_payment");
                                    financeList.wx_pay_fee = jsonArray.optJSONObject(i).optString("wx_pay_fee");
                                    financeList.ali_pay_fee = jsonArray.optJSONObject(i).optString("ali_pay_fee");
                                    financeList.buy_card = jsonArray.optJSONObject(i).optString("buy_card");
                                    financeList.refund_card = jsonArray.optJSONObject(i).optString("refund_card");
                                    financeList.violation_price = jsonArray.optJSONObject(i).optString("violation_price");
                                    financeList.area_outside = jsonArray.optJSONObject(i).optString("area_outside");
                                    financeList.rate_price = jsonArray.optJSONObject(i).optString("rate_price");
                                    financeList.order_count = jsonArray.optJSONObject(i).optString("order_count");
                                    finaceListAll.add(financeList);
                                }
                                if (statementAdapter != null) {
                                    statementAdapter.refresh(finaceListAll);
                                }
                            }
                        } else if ("1001".equals(jsonObject.optString("status"))) {
                            ToastUtil.showToast(jsonObject.optString("message"));
                        } else if ("1002".equals(jsonObject.optString("status"))) {
                            spUtils.clear();
                            ToastUtil.showToast(jsonObject.optString("message"));
                            JumpActivitys(LoginActivity.class);
                            finish();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
                if (finaceListAll.size() <= 0) {
                    emptyView.setVisibility(View.VISIBLE);
                    statementList.setVisibility(View.GONE);
                } else {
                    emptyView.setVisibility(View.GONE);
                    statementList.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void FailedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }



    @OnClick({R.id.back, R.id.calendar_img})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.calendar_img:
                AlertDialog.Builder builder = new AlertDialog.Builder(StatementAccountsActivity.this, R.style.RcDialog);
                View view1 = LayoutInflater.from(StatementAccountsActivity.this).inflate(R.layout.dialog_calnader, null);
                final TextView title=view1.findViewById(R.id.title);
                final TextView starttime=view1.findViewById(R.id.dialog_start_time);
                final TextView endtime=view1.findViewById(R.id.dialog_end_time);

                CalendarView calendarView=view1.findViewById(R.id.calendarview);

                calendarView.setSTimeSelListener(new CalendarView.CalendarSTimeSelListener() {
                    @Override
                    public void onSTimeSelect(Date date) {
                        if (date != null) {
                            String statrtTimeTxt= DateUtil.dateTostr(date, Constant.TFORMATE_YMD);
                            starttime.setText(statrtTimeTxt);
                            mstartTime=DateUtil.dateTostr(date, Constant.TFORMATE_YMD);
                        }
                    }
                });

                calendarView.setETimeSelListener(new CalendarView.CalendatEtimSelListener() {
                    @Override
                    public void onETimeSelect(Date date) {
                        if (date != null) {
                            String endTimeTxt= DateUtil.dateTostr(date, Constant.TFORMATE_YMD);
                            endtime.setText(endTimeTxt);
                            mendTime=DateUtil.dateTostr(date, Constant.TFORMATE_YMD);

                        }else {

                        }
                    }
                });
                final AlertDialog dialog = builder.create();
                dialog.setView(view1);
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
                TextView cancle = view1.findViewById(R.id.cancel);
                cancle.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                        loadDate();
                    }
                });
                TextView yes = view1.findViewById(R.id.yes);
                yes.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                        requestFinance(mstartTime,mendTime);
                        currentDate.setText(mstartTime+"至"+mendTime);

                    }
                });
                break;
                default:
                    break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (finaceListAll != null) {
            finaceListAll.clear();
        }
    }
}
